package com.snow.rbac.config;

import com.snow.common.exception.BadRequestException;
import com.snow.rbac.entity.UserInfo;
import com.snow.rbac.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * All rights Reserved, Designed By www.cusc.com
 *
 * @author yanke
 * @Title: TokenInterceptHandler
 * @Package com.snow.common.interceptor
 * @Description:类描述
 * @Email yanke@cu-sc.com
 * @version: v1.0.0
 * @date: 2021/7/1/0001 16:44
 * @Copyright: 2021  www.faw.com.cn Inc. All rights reserved. <br/>
 * Modification History:<br/>
 * Date         Author          Version            Description<br/>
 * *---------------------------------------------------------*<br/>
 * 2021/7/1/0001     Administrator           v1.0.0               修改原因<br/>
 * @since JDK 1.8
 */
@Slf4j
@Component
public class TokenInterceptHandler implements HandlerInterceptor {

    private final static String AUTHORIZATION = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String header = request.getHeader(AUTHORIZATION);
        header = StringUtils.substringAfter(header, "Bearer ");
        Optional.ofNullable(handler).orElseThrow(() -> new BadRequestException("token miss"));
        //token验证
        UserInfo userInfo = JwtUtils.parserJwt(header);
        Optional.ofNullable(handler).orElseThrow(() -> new BadRequestException("token error"));
        MDC.put("userId", String.valueOf(userInfo.getId()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
